package com.cetc.nsfx.util;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


public class StringUtil {
	// 判断IE或Firefox浏览器，确定下载文件名编码
	 	public static String encodeFilename(HttpServletRequest request,String fileName)  {
	 		String agent = request.getHeader("USER-AGENT");
	 		try {
	 			// IE
	 			if (null != agent && -1 != agent.indexOf("MSIE")) {
	 				fileName = URLEncoder.encode(fileName, "UTF8");
	 			// Firefox
	 			} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
	 				fileName = MimeUtility.encodeText(fileName, "UTF8", "B");
	 			}
	 		} catch (UnsupportedEncodingException e) {
	 			try {
	 				fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
	 			} catch (UnsupportedEncodingException e1) {
	 				e1.printStackTrace();
	 			}
	 			e.printStackTrace();
	 		}
	 		return fileName;
	 	}
	
	public static String arrayToStr(String [] str){
		StringBuffer sb=new StringBuffer("");
		for (int i = 0; i < str.length; i++) {
			sb.append(str[i]);
		}
		return sb.toString();
	}
	/**
	 * 将字符串转换为UTF-8格式
	 * @param str
	 * @return String
	 */
	public static String toUTF8(String str){
		try {
			str = new String(str.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}
	public final static Boolean isBlank(String para) {
		return para == null || para.equals("");
	}

	public final static Boolean isNotBlank(String para) {
		return !isBlank(para);
	}

	public static String escape(String source) {
		StringBuilder resultBuilder = new StringBuilder(source.length() * 6);
		char[] sourceChar = source.toCharArray();
		for (char c : sourceChar) {
			if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
				resultBuilder.append(c);
			} else if (c < 256) {
				resultBuilder.append("%");
				if (c < 16) {
					resultBuilder.append("0");
				}
				resultBuilder.append(Integer.toString(c, 16));
			} else {
				resultBuilder.append("%u");
				resultBuilder.append(Integer.toString(c, 16));
			}
		}
		return resultBuilder.toString();
	}

	public static String unescape(String source) {
		StringBuilder resultBuilder = new StringBuilder(source.length());
		int lastPos = 0, pos = 0;
		int sourceLength = source.length();
		char ch;
		while (lastPos < sourceLength) {
			pos = source.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (source.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(source.substring(pos + 2, pos + 6), 16);
					resultBuilder.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(source.substring(pos + 1, pos + 3), 16);
					resultBuilder.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					resultBuilder.append(source.substring(lastPos));
					lastPos = source.length();
				} else {
					resultBuilder.append(source.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return resultBuilder.toString();
	}
	public static String unescape(String source, String startTag) {
		StringBuilder resultBuilder = new StringBuilder(source.length());
		int lastPos = 0, pos = 0;
		int sourceLength = source.length();
		char ch;
		while (lastPos < sourceLength) {
			pos = source.indexOf(startTag, lastPos);
			if (pos == lastPos) {
				if (source.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(source.substring(pos + 2, pos + 6), 16);
					resultBuilder.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(source.substring(pos + 1, pos + 3), 16);
					resultBuilder.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					resultBuilder.append(source.substring(lastPos));
					lastPos = source.length();
				} else {
					resultBuilder.append(source.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return resultBuilder.toString();
	}
	
	
	public static final String xmlToJson(String xml) {
		try {
			
			Document document = DocumentHelper.parseText(xml);
			Element root = document.getRootElement();
			StringBuilder stringCache = new StringBuilder(xml.length() * 2);
			
			analyseElement(root, stringCache);
			
			return stringCache.toString();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return "{}";
	}
	
	private static final void analyseElement(Element element, StringBuilder stringCache) {
		List<Element> child = element.elements();
		Set<String> nameSet = new HashSet<String>();
		for (Element chi : child) {
			nameSet.add(chi.getName());
		}
		String[] nameArray = new String[0];
		nameArray = nameSet.toArray(nameArray);
		int nameSize = nameSet.size();
		String name;
		int m = 0;
		StringBuilder tmpCach = new StringBuilder(512);
		boolean use = false;
		for (int k = 0; k < nameSize; k ++) {
			name = nameArray[k];
			List<Element> typeList = element.elements(name);
			int typeSize = typeList.size();
			if (typeSize > 1) {
				tmpCach.append("[");
				use = true;
			}else{
				tmpCach.append(name).append(":");
			}
			if (typeSize > 1) {
				int t = 0;
				for (Element type : typeList) {
					tmpCach.append("{");
					if (type.elements().size() == 0) {
						tmpCach.append(name).append(":'").append(type.getText()).append("'");
					} else {
						tmpCach.append(name).append(":");
						analyseElement(type, tmpCach);
					}
					tmpCach.append("}");
					t++;
					if (t < typeSize) {
						tmpCach.append(",");
					}
				}
			} else {
				Element type = typeList.get(0);
				if (type.elements().size() == 0) {
					tmpCach.append("'").append(type.getText()).append("'");
				} else {
					analyseElement(type, tmpCach);
				}
			}
			m ++;
			if (m < nameSize) {
				tmpCach.append(",");
			}
			if (typeSize > 1) {
				tmpCach.append("]");
			}
		}
		if (use) {
			stringCache.append(tmpCach);
		}else{
			stringCache.append("{").append(tmpCach).append("}");
		}
		
	}
	public static boolean isNumeric(String str){
	   for(int i=str.length();--i>=0;){
	      int chr=str.charAt(i);
	      if(chr<48 || chr>57)
	         return false;
	   }
	   return true;
	}
	public static boolean isHave(String[] strs,String s){
	  for(int i=0;i<strs.length;i++){
	   if(strs[i].indexOf(s)!=-1){//循环查找字符串数组中的每个字符串中是否包含所有查找的内容
	    return true;//查找到了就返回真，不在继续查询
	   }
	  }
	  return false;//没找到返回false
	 }


}
